$(document).ready(function (){
require(['inputdrop'] ,function (inputdrop){

var index_list_url = "siem/eventIgnore/queryEventIgnoreList";

var index_list_col_header = [
							  {name:"",text:"" ,hideSearch:"hide",width:3},
							  {text : "策略名称" ,name : "apName",align:"left",width:27},
							  {text : "策略创建人" ,name : "createUserName",align:"left",width:24,hideSearch:true},
							  {text : "策略状态" ,name : "apStatus",align:"left",width:22,render:function(text){
									if (text ==1) {
										return '启用';
									}
									else{
										return '停用';
									}
								} ,searchRender:function (el){
									var data = [
													{text:"----" ,id:"-1"},
							  						{text:"启用" ,id:"1"},
							  						{text:"停用" ,id:"0"}
										  		];
									g_formel.select_render(el ,{
										data : data,
										name : "apStatus"
									});
							  }},
							  {text : "创建时间" ,name : "enterDate",align:"left",width:24,searchRender:function (el){
								index_render_div(el ,{type:"date", startKey:"enterStartDate" ,endKey:"enterEndDate"});
							  }}
							];

var index_list_col_oper = [
				  			  {icon : "rh-icon rh-edit" ,text : "修改" ,aclick :edit_template_init},
				  			  {icon : "rh-icon rh-delete" ,text : "删除" ,aclick :index_list_delete}
			   			  ];

var list_add_url = "siem/eventIgnore/addEventIgnore";

var list_update_url = "siem/eventIgnore/updEventIgnore";

var list_delete_url = "siem/eventIgnore/delEventIgnore";

var form_iplist_col_header = [
							  {text:'IP类型',name:"ipTypeName",align:"left",width:35},
							  {text:'IP范围',name:"ipRange",align:"left",width:65}
							 ];

var form_iplist_col_header3 = [
							  {text:'端口类型',name:"portTypeName",align:"left",width:35},
							  {text:'端口号',name:"portsValue",align:"left",width:65}
							 ];

var ipTypeObj = {
					"0":"源IP",
					"1":"目的IP",
					"2":"发生源"
				}

index_list_get({});

event_init();

function event_init ()
{
	$("#add_btn").click(function (){
		edit_template_init();
	});

	$("#export_btn").click(function (){
		export_init();
	});

	$("#import_btn").click(function (){
		import_init();
	});

	$("#immediately_btn").click(function (){
		immediately_init();
	});

	index_list_search_render($("um-search") ,{
		cbf : function (val){
			g_grid.refresh($("#table_div") ,{
				paramObj : {apName : val}
			})
		},
		placeholder : "请输入策略名称"
	})
}

function index_list_get(option)
{
	g_grid.render($("#table_div") ,{
		url : index_list_url,
 		header : index_list_col_header,
 		oper : index_list_col_oper,
 		operWidth : "100px",
 		dbIndex:1,
 		paramObj : option.paramObj,
 		isLoad : option.isLoad,
 		maskObj : option.maskObj,
 		dbClick : detail_template_init,
 		hasBorder : false,
		autoHeight : true,
		showCount : true
	});
}

function edit_template_init (rowData)
{
	var title = rowData ? "事件忽略策略修改" : "事件忽略策略添加";
	$.ajax({
		type: "GET",
		url: "module/policy_manage/event_ignore_policy_tpl.html",
		success : function(data){
			g_dialog.dialog($(data).find("[id=edit_template]") ,{
				width : "920px",
				init : init,
				initAfter : initAfter,
				title : title,
				saveclick : save_click,
				autoHeight:"autoHeight"
			});
		}
	});

	function init (el)
	{
		g_validate.init(el);
		// 天、月、周change事件
		var el_apCycle = el.find("[data-id=apCycle]");
		var el_eipCyclePeriod = el.find("[data-id=apCyclePeriod]");
		var el_validityStart = el.find("[data-id=validityStart]");
		var el_validityEnd = el.find("[data-id=validityEnd]");

		el_apCycle.change(function(){
			var tmp = $(this).val();
			el_eipCyclePeriod.removeAttr("disabled");
			el_eipCyclePeriod.find("option").remove();
			el_eipCyclePeriod.trigger("change");
			
			if (tmp == "3")
			{
				// 添加1-28天
				for (var i = 1; i < 29; i++)
				{
					el_eipCyclePeriod.append('<option value="'+i+'">'+i+'</option>');
				}
				el_validityStart.removeAttr("disabled");
				el_validityEnd.removeAttr("disabled");
			}
			else if (tmp == "2")
			{
				// 添加周一至周日
				el_eipCyclePeriod.removeAttr("disabled");
				el_eipCyclePeriod.append('<option value="0">星期日</option>');
				el_eipCyclePeriod.append('<option value="1">星期一</option>');
				el_eipCyclePeriod.append('<option value="2">星期二</option>');
				el_eipCyclePeriod.append('<option value="3">星期三</option>');
				el_eipCyclePeriod.append('<option value="4">星期四</option>');
				el_eipCyclePeriod.append('<option value="5">星期五</option>');
				el_eipCyclePeriod.append('<option value="6">星期六</option>');

				el_validityStart.removeAttr("disabled");
				el_validityEnd.removeAttr("disabled");
			}
			else if (tmp == "1")
			{
				el_eipCyclePeriod.attr("disabled","disabled");
				el_validityStart.removeAttr("disabled");
				el_validityEnd.removeAttr("disabled");
			}
			else
			{
				el_eipCyclePeriod.attr("disabled","disabled");
				el_validityStart.attr("disabled","disabled");
				el_validityEnd.attr("disabled","disabled");
				el_validityStart.val("");
				el_validityEnd.val("");
				g_validate.clear([el_validityStart,el_validityEnd]);
			}
			$("[data-id=apCyclePeriod]").trigger("change");
		});

		el_validityStart.click(function(){
			if($(this).val() == "")
			{
				$(this).val("00:00:00");
			}				
		});
		el_validityEnd.click(function(){
			if($(this).val() == "")
			{
				$(this).val("00:00:00");
			}				
		});
	}

	function initAfter (el)
	{
		var eventType;
		// 获取第一个表格的数据
		um_ajax_get({
			url : "siem/eventIgnore/queryEventKindInfo",
			maskObj : el,
			successCallBack : function(data){
				data.unshift({eventKindName:"---" ,eventKindId:"-11"});
				g_formel.selectEl_render(el.find("[data-id=eventTypeComboBox]"),{
					data : data,
					text : "eventKindName",
					id : "eventKindId"
				});
				eventType = el.find("[data-id=eventTypeComboBox]").val();
			}
		});
		
		el.find("[data-id=eventTypeComboBox]").change(function(){
			eventType = el.find("[data-id=eventTypeComboBox]").val();
			event_list_get(eventType);
		});

		var el_table_left1 = el.find("[id=eventList_left_table1]");
		var el_table_right1 = el.find("[id=eventList_right_table1]");

		// 第一个左右按钮点击事件
		el.find("[id=chevron-left2]").click(function (){
			var rightDataArray = g_grid.getData(el_table_right1 ,{chk:true});
			if (rightDataArray.length == 0)
			{
				g_dialog.operateAlert(el ,index_select_one_at_least_msg ,"error");
				return false;
			}
			g_grid.removeData(el_table_right1);
			var eventType = el.find("[data-id=eventTypeComboBox]").val();
			event_list_get(eventType);
		});

		el.find("[id=chevron-right2]").click(function (){
			var leftDataArray = g_grid.getData(el_table_left1 ,{chk:true});
			if (leftDataArray.length == 0)
			{
				g_dialog.operateAlert(el ,index_select_one_at_least_msg ,"error");
				return false;
			}
			g_grid.removeData(el_table_left1);
			g_grid.addData(el_table_right1 ,leftDataArray);
		});

		g_grid.render(el_table_left1,{
			 header:[{text:"事件名称",name:"eventName",align:"left"}],
			 data:[],
			 hideSearch:true,
			 paginator:false
		});

		g_grid.render(el_table_right1,{
			 header:[{text:"事件名称",name:"eventName",align:"left"}],
			 data:[],
			 hideSearch:true,
			 paginator:false
		});

		// 第二个list
		var ipList_table = el.find("[id=ipList_table2]");

		g_grid.render(ipList_table,{
			data:[],
			header:form_iplist_col_header,
			paginator:false,
			isLoad:false,
			hideSearch:true
		});

		var el_startIp = el.find("[data-id=startIp]");
		var el_endIp = el.find("[data-id=endIp]");
		var el_ipV6 = el.find("[data-id=ipV6]");

		// IP类型点击事件
		var ipVersion_radio = el.find("[name=ipVersion]")
		ipVersion_radio.click(function (){
			if ($(this).val() == "0")
			{
				el_startIp.removeAttr("disabled");
				el_endIp.removeAttr("disabled");
				el_ipV6.attr("disabled" ,"disabled");
				g_validate.clear(el_ipV6);
				el_ipV6.val("");
			}
			else
			{
				el_startIp.attr("disabled" ,"disabled");
				el_endIp.attr("disabled" ,"disabled");
				el_ipV6.removeAttr("disabled");
				g_validate.clear([el_startIp ,el_endIp]);
				el_startIp.val("");
				el_endIp.val("");
			}
		});

		// 右移事件
		var ipList = [];
		el.find("[id=chevron-right]").click(function (){
			if (!g_validate.validate($("#left")))
			{
				return false;
			}
			if (!g_validate.ipValidate(el.find("[data-id=startIp]") ,el.find("[data-id=endIp]"))){
				return false;
			}	
			el.find("[name=ipType]").each(function (){
				if ($(this).is(":checked"))
				{
					var obj = new Object();
					obj.ipType = $(this).val();
					obj.ipTypeName = $(this).closest("label").find("span").text();
					obj.ipAddrType = el.find("[name=ipVersion]:checked").val();
					obj.startIp = el_startIp.val();
					obj.endIp = el_endIp.val();
					obj.ipV6 = el_ipV6.val();
					obj.startIp && (obj.ipRange = obj.startIp + "-" + obj.endIp);
					obj.ipV6 && (obj.ipRange = obj.ipV6);
					ipList.push(obj);
				}
			});
			if (ipList.length == 0)
			{
				g_dialog.operateAlert(el ,"请选择IP类型" ,"error");
				return false;
			}
			g_grid.addData(el.find("[id=ipList_table2]") ,ipList);

			el.find("[id=left]").find("[type=text]").val("");
			el.find("[name=ipType]").removeAttr("checked");
			ipList = [];
		});

		// 左移事件
		el.find("[id=chevron-left4]").click(function (){
			var data = g_grid.getData(el.find("#ipList_table2") ,{chk:true});
			if (data.length == 0)
			{
				g_dialog.operateAlert(el ,"请选择一条记录。" ,"error");
			}
			else if (data.length > 1)
			{
				g_dialog.operateAlert(el ,"只允许选择一条记录。" ,"error");
			}
			else 
			{
				el.find("[name=ipType][value="+data[0].ipType+"]")[0].checked =true;
				el.find("[name=ipVersion][value="+data[0].ipAddrType+"]").click();
				if(data[0].ipRange.indexOf("-")>0)
				{	
					var array = data[0].ipRange.split("-");
					el_startIp.val(array[0]);
					el_endIp.val(array[1]);
				}
				else 
				{
					el_ipV6.val(data[0].ipRange);
				}
			}
			g_grid.removeData(el.find("[id=ipList_table2]"));	
		});

		// 第三个list
		var ipList_table3 = el.find("[id=ipList_table3]");

		g_grid.render(ipList_table3,{
			data:[],
			header:form_iplist_col_header3,
			paginator:false,
			isLoad:false,
			hideSearch:true
		});

		var port = el.find("[data-id=emailTitle1]");

		// 右移事件
		var ipList = [];
		el.find("[id=chevron-right3]").click(function (){
			if (!g_validate.validate($("#left3")))
			{
				return false;
			}
			el.find("[name=portTypeValue]").each(function (){
				if ($(this).is(":checked"))
				{
					var obj = new Object();
					obj.portTypeValue = $(this).val();
					obj.portTypeName = $(this).closest("label").find("span").text();
					obj.portsValue = port.val();
					ipList.push(obj);
				}
			});
			if (ipList.length == 0)
			{
				g_dialog.operateAlert(el ,"请填写端口号" ,"error");
				return false;
			}
			g_grid.addData(el.find("[id=ipList_table3]") ,ipList);

			el.find("[id=left3]").find("[type=text]").val("");
			el.find("[name=portTypeValue]").removeAttr("checked");
			ipList = [];
		});

		// 左移事件
		el.find("[id=chevron-left3]").click(function (){
			var data = g_grid.getData(el.find("#ipList_table3") ,{chk:true});
			if (data.length == 0)
			{
				g_dialog.operateAlert(el ,"请选择一条记录。" ,"error");
			}
			else if (data.length > 1)
			{
				g_dialog.operateAlert(el ,"只允许选择一条记录。" ,"error");
			}
			else 
			{
				el.find("[name=portTypeValue][value="+data[0].portTypeValue+"]")[0].checked =true;
				g_grid.removeData(el.find("[id=ipList_table3]"));
				el.find("[data-id=emailTitle1]").val(data[0].portsValue);
			}
		});

		// 数据回显
      	if (rowData)
	  	{
		  um_ajax_get({
			  url :"/siem/eventIgnore/queryEventIgnore",
			  paramObj : {id:rowData.apId},
			  isLoad: false,
			  successCallBack : function (data){
				  edit_template_render(el ,data ,rowData);									  
			  }
		  });
	   }


	}

	function save_click (el ,saveObj)
	{
		//确定之前不校验左边的ip
		el.find("[data-id=ipV6]").removeAttr("validate");
		el.find("[data-id=startIp]").removeAttr("validate");
		el.find("[data-id=endIp]").removeAttr("validate");
		el.find("[data-id=emailTitle1]").removeAttr("validate");

		var flag = true;

		if (!flag)
		{
			el.find("[data-id=ipV6]").attr("validate","required,ipv6");
			el.find("[data-id=startIp]").attr("validate","required,ipv4");
			el.find("[data-id=endIp]").attr("validate","required,ipv4");
			return false;
		}

		var startTime = el.find("[data-id=validityStart]").val();
		var endTime = el.find("[data-id=validityEnd]").val();  
	    if((startTime > endTime) || ((startTime == endTime) && ((startTime || endTime) != "")))
	    {  
	        g_dialog.dialogTip(el ,{msg:"执行时间的起始时间必须小于终止时间。"});
	        return false;  
	    }
		if(!g_validate.validate(el))
		{
			return false;
		}

		var eventIdArray = g_grid.getIdArray(el.find("[id=eventList_right_table1]"),{attr:"evenId"});
		for (var i = 0; i < eventIdArray.length; i++) {
			eventIdArray[i] = {evenId:eventIdArray[i]};
		}
		if(eventIdArray.length == 0)
		{
			g_dialog.operateAlert(el ,"请选择事件。" ,"error");
			return false;
		}

		var obj = {};
		obj.eventIgonreStore = saveObj;

		obj.eventStore = eventIdArray;

		obj.ipRecordStore = g_grid.getData(el.find("[id=ipList_table2]"));

		obj.portRecordStore = g_grid.getData(el.find("[id=ipList_table3]"));

		obj.eventIgonreStore.eventGrade = saveObj.eventGrade.join(",");
	
		for (var i = 0; i < obj.ipRecordStore.length; i++) {
			if (obj.ipRecordStore[i].ipV6)
			{
				obj.ipRecordStore[i].startIp = obj.ipRecordStore[i].ipV6;
				obj.ipRecordStore[i].endIp = obj.ipRecordStore[i].ipV6;
			}
			obj.ipRecordStore[i].ipRadioStatus = obj.ipRecordStore[i].ipAddrType;
		}

		var flag_url = list_add_url;

		if (rowData)
		{
			flag_url = list_update_url;
			obj.eventIgonreStore.apId = rowData.apId;
		};

		um_ajax_post({
			url : flag_url,
			paramObj : obj,
			maskObj : el,
			successCallBack : function (data){
				g_dialog.operateAlert(null ,"操作成功！");
				g_dialog.hide(el);
				index_list_get({paramObj:null,isLoad:true,maskObj:"body"});
			}
		});
	}
}

function event_list_get(eventType)
{
	var el = $("#edit_template");
	var eventType = eventType;
	var eventStore = g_grid.getData(el.find("[id=eventList_right_table1]"));
	g_grid.render(el.find("[id=eventList_left_table1]"),{
		 header:[{text:"事件名称",name:"eventName",align:"left"}],
		 url:"siem/eventIgnore/queryEventNoSelected",
		 paramObj:{eventType:eventType,eventStore:eventStore},
		 isLoad:false,
		 maskObj:"body",
		 hideSearch:true,
		 paginator:false
	});
}


function edit_template_render(el ,data ,rowData)
{
	//回显input和下拉框
	el.umDataBind("render" ,rowData);

	// 回显事件等级
	el.find("[data-id=eventGrade]").val(data.eventIgnoreStore.eventGrade.split(","));
	el.find("[data-id=eventGrade]").oneTime(10 ,function (){
		el.find("[data-id=eventGrade]").trigger("change");
	});

	// 回显周期列表
	if (data.eventIgnoreStore.apCycle != "0")
	{
		el.find("[data-id=apCycle]").val(data.eventIgnoreStore.apCycle);
		el.find("[data-id=apCycle]").trigger("change");

		el.find("[data-id=apCyclePeriod]").val(data.eventIgnoreStore.apCyclePeriod);
		el.find("[data-id=apCyclePeriod]").trigger("change");

		el.find("[data-id=validityStart]").val(data.eventIgnoreStore.validityStart);
		el.find("[data-id=validityEnd]").val(data.eventIgnoreStore.validityEnd);
	}

	// 回显事件类型
	g_grid.addData(el.find("[id=eventList_right_table1]") ,data.eventStore);
	// 回显IPLIST
	for (var i = 0; i < data.ipRecordStore.length; i++)
	{
		data.ipRecordStore[i].ipRange = data.ipRecordStore[i].ipAllName;
		data.ipRecordStore[i].ipTypeName = ipTypeObj[data.ipRecordStore[i].ipType];
		data.ipRecordStore[i].ipAddrType = data.ipRecordStore[i].ipRadioStatus;
	}
	g_grid.addData(el.find("[id=ipList_table2]") ,data.ipRecordStore);
	// 回显端口
	g_grid.addData(el.find("[id=ipList_table3]") ,data.portRecordStore);
}

function export_init()
{
	var queryObj = $("[class=um-grid-search-tr]").umDataBind("serialize" ,"search-data");
	var queryJson = JsonTools.encode(queryObj);
	var array = g_grid.getIdArray($("#table_div") ,{chk:true ,attr:"apId"});
	window.location.href = index_web_app + index_soc_prefix + "siem/eventIgnore/exportSEGXml" + "?asset="+array.join(",")+"&queryStr="+encodeURI(queryJson);
}

function import_init()
{
	$.ajax({
		type: "GET",
		url: "module/policy_manage/event_ignore_policy_tpl.html",
		success :function(data)
		{
			g_dialog.dialog($(data).find("[id=import_template]"),{
				width:"500px",
				init:init,
				title:"事件忽略策略导入",
				saveclick: save_click
			});
		}
	});
	function init(el)
	{
		index_create_upload_el(el.find("[id=ptMap]"));
		el.find("[class=icon-trash]").click(function (){
			el.find("[data-id=up_name]").val("");
		});
	}
	function save_click(el,saveObj)
	{
		var validate_result = g_validate.fileSuffixLimit(el.find('[id=ptMap]').val(),"xml",true,true);
		if(!validate_result.flag){
			g_dialog.operateAlert(null,validate_result.msg,"error");
			return false;
		}

		var el_form = el.find("form");

		um_ajax_file(el_form,{
			url : "siem/eventIgnore/secEventGenImport",
			successCallBack : function(){
				g_dialog.operateAlert();
				g_dialog.hide(el);
				index_list_get({paramObj:null,isLoad:false,maskObj:"body"});
			}
		});
			
	}

}

function immediately_init ()
{
	var idArray = g_grid.getIdArray($("#table_div") ,{chk:true,attr:"apId"});
	if (idArray.length == 0) 
	{
		g_dialog.operateAlert($("#table_div") ,index_select_one_at_least_msg ,"error");
		return false;
	}
	var ids = idArray.join(",");
	um_ajax_post({
		url:"siem/eventIgnore/doExcute",
		paramObj:{taskId:ids},
		isLoad:"true",
		maskObj:"body",
		successCallBack:function(data){
			g_dialog.operateAlert();
			index_list_get({paramObj:null,isLoad:false,maskObj:"body"});
		}
	});
}

function index_list_delete (rowData)
{
	g_dialog.operateConfirm("确认删除此记录么" ,{
		saveclick : function (){
			um_ajax_post({
				url : list_delete_url,
				paramObj : {apId: rowData.apId},
				maskObj : $("#table_div"),
				successCallBack : function(data){
					g_grid.refresh($("#table_div"));
					g_dialog.operateAlert(null ,"操作成功！");
				}
			});
		}
	});
}

function detail_template_init (rowData)
{
	$.ajax({
		type: "GET",
		url: "module/policy_manage/event_ignore_policy_tpl.html",
		isLoad:true,
		maskObj:"body",
		success :function(data)
		{
			g_dialog.dialog($(data).find("[id=detail_template]"),{
				width : "800px",
				init : init,
				initAfter : initAfter,
				title : "事件忽略策略详细信息",
				isDetail : true
			});
		}
	});

	function init (el)
	{
		var event_name_header = [
						{text:'事件名称',name:"eventName",align:"left"}
				   ];
		g_grid.render(el.find("[id=event_name_div]"),{
			data:[],
			header:event_name_header,
	 		paginator:false,
			isLoad:false,
			allowCheckBox:false,
			hideSearch:true
		});

		var ip_type_header = [
						{text:'IP类型',name:"ipTypeName",align:"left"},
						{text:'IP',name:"ipAllName",align:"left"}
				   ];
		g_grid.render(el.find("[id=ip_type_div]"),{
			data:[],
			header:ip_type_header,
	 		paginator:false,
			isLoad:false,
			allowCheckBox:false,
			hideSearch:true
		});

		var port_type_header = [
						{text:'端口类型',name:"portTypeName",align:"left"},
						{text:'端口号',name:"portsValue",align:"left"}
				   ];
		g_grid.render(el.find("[id=port_type_div]"),{
			data:[],
			header:port_type_header,
	 		paginator:false,
			isLoad:false,
			allowCheckBox:false,
			hideSearch:true
		});		
	}

	function initAfter (el)
	{
		um_ajax_get({
			url : "siem/eventIgnore/queryEventIgnore",
			paramObj : {id:rowData.apId},
			maskObj : el,
			successCallBack : function (data){
				g_grid.addData(el.find("[id=event_name_div]") ,data.eventStore);
				g_grid.addData(el.find("[id=ip_type_div]") ,data.ipRecordStore);
				g_grid.addData(el.find("[id=port_type_div]") ,data.portRecordStore);
				//回显input和下拉框
				el.umDataBind("render" ,data.eventIgnoreStore);

				// 回显周期列表
				var apCycle;
				var apCyclePeriod;
				if(data.eventIgnoreStore.apCycle == "1")
				{
					apCycle = "天";
					apCyclePeriod = "";
				}
				else if(data.eventIgnoreStore.apCycle == "2")
				{
					apCycle = "周";
					switch(data.eventIgnoreStore.apCyclePeriod)
					{
						case "0":
						apCyclePeriod =  "日";
						break;
						case "1":
						apCyclePeriod =  "一";
						break;
						case "2":
						apCyclePeriod =  "二";
						break;
						case "3":
						apCyclePeriod =  "三";
						break;
						case "4":
						apCyclePeriod =  "四";
						break;
						case "5":
						apCyclePeriod =  "五";
						break;
						case "6":
						apCyclePeriod =  "六";
						break;
					}
				}
				else if(data.eventIgnoreStore.apCycle == "3")
				{
					apCycle = "月";
					apCyclePeriod = data.eventIgnoreStore.apCyclePeriod+"日";
				}
				
				console.log(data.eventIgnoreStore.apCycle)

				if(data.eventIgnoreStore.apCycle != null && data.eventIgnoreStore.apCycle != "-1"
					&& data.eventIgnoreStore.apCycle != "0")
				{
					el.find("[data-id=circle_info]").text("每"+apCycle+apCyclePeriod+" "+data.eventIgnoreStore.validityStart+"-"+data.eventIgnoreStore.validityEnd);
				}
				else
				{
					el.find("[data-id=circle_info]").text("无");
				}
			}
		});			
	}
}


});
});